import { useRef, useState } from "react"
import BookList from "./components/Book/BookList"
import type { BookResponse } from "../../api/welcome/type"
import { Button, message, Space } from "antd"
import { logoutApi } from "../../api/welcome/logout"
import { useLoaderData, useNavigate } from "react-router"
import AIChat from "./components/AI/AIChat"
import UserForm, { type UserFormRef } from "./components/UserForm"


const WelcomePage: React.FC = () => {
  const [bookList, setBookList] = useState<BookResponse[]>([])
  const userFormRef = useRef<UserFormRef>(null)
  const user = useLoaderData()
  let navigate = useNavigate()

  const logout = async () => {
    const res = await logoutApi()
    if (res.code == 200) {
      localStorage.clear()
      navigate('/login')
      message.success('安全退出')
    }
  }

  const appendBook = (bookList: BookResponse[], isAppend: boolean = true) => {
    if (isAppend) {
      setBookList(old => [...old, ...bookList])
    } else {
      setBookList(bookList)
    }
  }

  return <>
    <div className="container m-auto my-7 p-6">
      <div className="flex justify-between items-center mb-5">
        <div className="flex gap-3">
          <div className="avatar w-12 h-12 avatar-placeholder">
            <div className="bg-linear-to-br from-[#4f46e5] to-[#06b6d4] text-neutral-content w-16 rounded-xl">
              <span className="text-xl">AI</span>
            </div>
          </div>
          <div>
            <h1 className="text-lg font-bold">智能电子书馆</h1>
            <div className="text-xs text-[#596270]">基于AI Agent 的智能电子资源平台！</div>
          </div>
        </div>
        <Space>
          <Button hidden={user?.role > 1} type="primary" size="large" onClick={() => userFormRef.current?.openModal()}>添加用户</Button>
          <Button type="primary" size="large" onClick={() => logout()}>退出登录</Button>
        </Space>
      </div>
      <div className="flex gap-4 justify-center min-h-[60vh] max-h-[80vh]">
        <div className="card shadow-sm w-1/3">
          <div className="card-body">
            <BookList bookList={bookList} appendBook={appendBook} />
          </div>
        </div>
        <div className="card shadow-sm w-2/3">
          <div className="card-body">
            <AIChat />
          </div>
        </div>
      </div>
    </div>
    <UserForm ref={userFormRef} />
  </>

}


export default WelcomePage